package com.example.cc.mygit.view.code;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.example.cc.mygit.GitApplication;
import com.example.cc.mygit.R;
import com.example.cc.mygit.model.Project;
import com.example.cc.mygit.source.GitAppConfig;
import com.haibin.androidbase.activity.BaseBackActivity;
import com.haibin.androidbase.adapter.BaseRecyclerAdapter;

import butterknife.Bind;

/**
 * Created by cc on 2016/12/13.
 */

public class CodeActivity extends BaseBackActivity implements
        BaseRecyclerAdapter.OnItemClickListener, CodeContract.ActionView {

    @Bind(R.id.rv_path)
    RecyclerView mRecyclerPath;

    private PathAdapter mAdapter;

    private CodeFragment mFragment;
    private CodePresenter mPresenter;

    public static void show(Context context, Project project) {
        Intent intent = new Intent(context, CodeActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("project", project);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_code;
    }


    @Override
    protected void initView() {
        super.initView();
        Project project = (Project) getIntent().getExtras().getSerializable("project");
        mRecyclerPath.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
        mAdapter = new PathAdapter(this);
        mAdapter.addItem(project.getName());
        mRecyclerPath.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
        mFragment = CodeFragment.newInstance(project);
        addFragment(R.id.fl_content,mFragment);
        mPresenter = new CodePresenter(mFragment,
                this,
                project,
                GitApplication.getConfig().getUser());
        mPresenter.start();

    }

    @Override
    public void onItemClick(int position, long itemId) {

        if (mPresenter.isLoading)
            return;
        mPresenter.preLoad(position);
        mAdapter.removeAll(position);
    }

    @Override
    public void onAddPath(String path) {

        mAdapter.addItem(path);
    }

    @Override
    public void onBackPressed() {
        if (mPresenter.isCanBack())
        super.onBackPressed();
        else{
            if (mPresenter.isLoading)
                return;
            int p= mAdapter.getItems().size()-2;
            mPresenter.preLoad(p);
            mAdapter.removeAll(p);
        }
    }
}
